package com.beiye.drivertransport.safelearn;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.PayMentBean;
import com.beiye.drivertransport.bean.UserVipCheckBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.githang.statusbar.StatusBarCompat;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.UUID;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//日常培训支付界面
public class SpecifiedLearningPayActivity extends TwoBaseAty {

    ImageView img_payback;


    TextView tv_content;

    TextView tv_price;

    TextView tv_pay3;//购买

    TextView tv_money2;//差值

    TextView tvMoney1;

    LinearLayout lePrejob1;

    LinearLayout lePrejob2;

    ImageView imgPay;

    TextView tvPay2;

    TextView tvPay4;
    private PopupWindow mUserPopWindow;
    private IWXAPI api;


    private String orgId;
    private String utchSn;
    private Double amount;
    private Double balance;
    private Double muAmount;
    private String chName;


    @Override
    public int getLayoutId() {
        return R.layout.activity_specifiedlearn_payment;
    }


    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_payback) {
            finish();
        } else if (id == R.id.tv_pay3) {
            payment();//支付方法
        }
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        utchSn = bundle.getInt("utchSn") + "";
        orgId = bundle.getString("orgId");
        amount = bundle.getDouble("amount");
        balance = bundle.getDouble("balance");
        chName = bundle.getString("chName");
        muAmount = amount - balance;//需付金额

        tv_price.setText(getTwoDecimal(amount) + "元");
        tvMoney1.setText(getTwoDecimal(balance) + "元");
        tv_money2.setText("需付金额：" + getTwoDecimal(muAmount) + "元");

        if (muAmount > 0) { //需微信支付
            if (balance <= 0) { //没有余额
                lePrejob1.setVisibility(View.GONE);
            }
            tvPay2.setText("微信支付");
            imgPay.setImageResource(R.mipmap.wechatpay);
        } else { //余额支付
            tv_money2.setText("本次购买金额充足");
            tvPay2.setText("余额支付");
            imgPay.setImageResource(R.mipmap.balancepayment);
        }

        tvPay4.setText(chName);
        tv_content.setText("本课程学习内容仅用于" + chName + "，如需购买其他学习内容，请返回点击其他学习页面。");

    }


    //支付方法
    public void payment() {

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        String phoneSign = getPhoneSign();//设备的唯一标识


        if (muAmount > 0) { //需微信支付金额
            boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if (!isPaySupported) {
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(SpecifiedLearningPayActivity.this);
                builder1.setMessage("该微信版本不支持微信支付或者未安装微信软件");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ;
                    }
                });
                builder1.create().show();
                return;
            }
            Toast.makeText(SpecifiedLearningPayActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
            tv_pay3.setEnabled(false);//微信支付
            new Login().courseBuyMt(userId, orgId, 2 + "", getTwoDecimal(amount), getTwoDecimal(muAmount), utchSn + "", "APP", Constants.APP_ID, phoneSign, this, 1);
        } else {
            tv_pay3.setEnabled(false);//余额支付

            new Login().courseBuyMt(userId, orgId, 3 + "", getTwoDecimal(amount), "0", utchSn + "", "APP", Constants.APP_ID, phoneSign, this, 4);
        }

    }

    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
        // 根据返回码的不同，设置参数
        if (requestCode == 0) {
            if (resultCode == 1) {
                payment();//支付方法
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //     EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningPayActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }


    @Override
    public void initData() {
        img_payback = (ImageView) findViewById(R.id.img_payback);
        tv_content = (TextView) findViewById(R.id.tv_content);
        tv_price = (TextView) findViewById(R.id.tv_money);
        tv_pay3 = (TextView)findViewById(R.id.tv_pay3);
        tv_money2 = (TextView)findViewById(R.id.tv_money2);
        tvMoney1 = (TextView) findViewById(R.id.tv_money1);
        lePrejob1 = (LinearLayout) findViewById(R.id.le_prejob1);
        lePrejob2 = (LinearLayout) findViewById(R.id.le_prejob2);
        imgPay = (ImageView) findViewById(R.id.img_pay);
        tvPay2 = (TextView) findViewById(R.id.tv_pay2);
        tvPay4 = (TextView) findViewById(R.id.tv_pay4);
        //注册EventBus
        //    EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

    }

    /**
     * 将数据保留两位小数
     */
    private String getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#0.00");
        String yearString = dFormat.format(num);
        return yearString;
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);

        if (what == 1) {
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningPayActivity", Context.MODE_PRIVATE);

            PayMentBean payMentBean = JSON.parseObject(result, PayMentBean.class);
            String msg = payMentBean.getMsg();//支付订单系列号
            SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit1 = sp1.edit();
            edit1.putString("msg", msg);
            edit1.putInt("paytag", 9);
            edit1.commit();
            PayMentBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
            if (paydata != null) {
                api.registerApp(Constants.APP_ID);
                PayReq req = new PayReq();
                req.appId = Constants.APP_ID;
                req.packageValue = "Sign=WXPay";
                req.partnerId = paydata.getPartnerid();
                req.prepayId = paydata.getPrepayid();
                req.nonceStr = paydata.getNoncestr();
                req.timeStamp = paydata.getTimestamp();
                req.sign = paydata.getSign();
                api.sendReq(req);
                finish();
            }
            tv_pay3.setEnabled(true);
        } else if (what == 4) {
            EventBus.getDefault().post(new MessageEvent(MessageEvent.TYPE_19));
            finish();
        }
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        super.onError(result, call, response, what);
        if (what == 1) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();

        } else if (what == 4) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);

            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
    }

    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign() {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }

    /**
     * 得到全局唯一UUID
     */
    private String uuid;

    public String getUUID() {
        SharedPreferences mShare = getSharedPreferences("uuid", MODE_PRIVATE);
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid", uuid).commit();
        }
        return uuid;
    }
    /**
     * 验证输入身份证号
     *
     * @param
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
//    public  boolean IsIDcard(String str) {
//        String regex = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
//        return match(regex, str);
//    }
    /**
     * @param regex
     * 正则表达式字符串
     * @param str
     * 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
//    private  boolean match(String regex, String str) {
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(str);
//        return matcher.matches();
//    }
}
